import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { IReducerState } from '@/store/root-reducer';

// Define the initial state using that type
const initialState: IReducerState = {
  loading: false,
  entities: [],
  totalCount: 0,
  entity: {},
  // 当前 entiy 在 entities 中的 index
  index: -1,
  // 当前 entities 在 total 中的 offset
  offset: 0,
  error: null,
  key: 'id',
};

export const applicationSlice = createSlice({
  name: 'application',
  // `createSlice` will infer the state type from the `initialState` argument
  initialState,
  reducers: {
    catchError: (state, action) => {
      state.error = action.payload.error;
      state.loading = false;
    },
    start: (state) => {
      state.error = null;
      state.loading = true;
    },
    end: (state) => {
      state.loading = false;
    },
    entitiesFetched: (state, action) => {
      const { totalCount, entities, offset } = action.payload;
      state.loading = false;
      state.error = null;
      state.entities = entities;
      state.totalCount = totalCount;
      state.offset = offset;
    },
    entityCreated: (state, action) => {
      state.loading = false;
      state.error = null;
      state.totalCount = state.totalCount + 1;
      state.entities = [...state.entities, action.payload.entity];
    },
    entitySet: (state, action) => {
      state.error = null;
      state.entity = action.payload.entity;
      state.index = action.payload.index;
    },
    entityDeleted: (state, action) => {
      state.error = null;
      state.loading = false;
      state.entity = {};
      state.index = -1;
      state.entities = state.entities.filter(
        (el) => el[state.key] !== action.payload.key
      );
    },
    entityUpdated: (state, action) => {
      state.error = null;
      state.loading = false;
      state.entity = action.payload.entity;
      state.entities = state.entities.map((entity) =>
        entity[state.key] === action.payload.entity[state.key]
          ? action.payload.entity
          : entity
      );
    },
  },
});
